package cn.lili.modules.order.order.serviceimpl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.json.JSONUtil;
import cn.lili.common.enums.ResultCode;
import cn.lili.common.exception.ServiceException;
import cn.lili.common.security.context.UserContext;
import cn.lili.common.security.enums.SceneEnums;
import cn.lili.common.thread.ThreadConfig;
import cn.lili.common.utils.CurrencyUtil;
import cn.lili.common.utils.ResultUtil;
import cn.lili.common.vo.PageVO;
import cn.lili.common.vo.ResultMessage;
import cn.lili.modules.distribution.client.DistributionClient;
import cn.lili.modules.distribution.entity.enums.DistributionStatusEnum;
import cn.lili.modules.goods.client.GoodsSkuClient;
import cn.lili.modules.goods.entity.dos.GoodsSku;
import cn.lili.modules.member.client.UnionClient;
import cn.lili.modules.member.client.UserClient;
import cn.lili.modules.member.entity.dos.CityDistribution;
import cn.lili.modules.member.entity.dos.Union;
import cn.lili.modules.member.entity.dos.User;
import cn.lili.modules.member.entity.enums.ComissStatusEnum;
import cn.lili.modules.operationcenter.client.OperationCenterClient;
import cn.lili.modules.operationcenter.entity.dos.OperationCenter;
import cn.lili.modules.order.aftersale.entity.dos.AfterSale;
import cn.lili.modules.order.order.entity.constant.OrderConstant;
import cn.lili.modules.order.order.entity.dos.*;
import cn.lili.modules.order.order.entity.dto.*;
import cn.lili.modules.order.order.entity.enums.OrderFlowStatusEnum;
import cn.lili.modules.order.order.entity.enums.ProfitSharingStatusEnum;
import cn.lili.modules.order.order.entity.params.DirectPushOrderParams;
import cn.lili.modules.order.order.entity.vo.*;
import cn.lili.modules.order.order.mapper.OrderFlowMapper;
import cn.lili.modules.order.order.mapper.OrderMapper;
import cn.lili.modules.order.order.service.*;
import cn.lili.modules.payment.client.PaymentClient;
import cn.lili.modules.payment.entity.dos.OutOrderDetailLog;
import cn.lili.modules.payment.entity.dos.PaymentSubsidies;
import cn.lili.modules.payment.entity.dto.ProfitSharingRequestDTO;
import cn.lili.modules.payment.entity.dto.SubsidiesParams;
import cn.lili.modules.payment.entity.enums.OutOrderLogStatusEnums;
import cn.lili.modules.payment.entity.enums.PaymentMethodEnum;
import cn.lili.modules.payment.entity.vo.OutOrderLogVO;
import cn.lili.modules.promotion.client.GreenClient;
import cn.lili.modules.promotion.client.GreenCommonwealContributionClient;
import cn.lili.modules.promotion.client.ReturnActivityClient;
import cn.lili.modules.promotion.entity.dos.GreenContributionInfo;
import cn.lili.modules.promotion.entity.dos.GreenCommonwealContribution;
import cn.lili.modules.promotion.entity.enums.GreenAmountInfoStatusEnum;
import cn.lili.modules.promotion.entity.enums.GreenAmountInfoTypeEnum;
import cn.lili.modules.store.client.StoreClient;
import cn.lili.modules.store.entity.dos.Store;
import cn.lili.modules.store.entity.vos.StoreFlowPayDownloadVO;
import cn.lili.modules.system.client.DictionaryClient;
import cn.lili.modules.system.client.SettingClient;
import cn.lili.modules.system.constants.DictConstant;
import cn.lili.modules.system.entity.dos.Setting;
import cn.lili.modules.system.entity.dto.DistributionSetting;
import cn.lili.modules.system.entity.enums.SettingEnum;
import cn.lili.mybatis.util.PageUtil;
import cn.lili.mybatis.util.SceneHelp;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.api.PayApi;
import com.api.UserApi;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.transaction.annotation.ShardingTransactionType;
import org.apache.shardingsphere.transaction.core.TransactionType;
import org.jetbrains.annotations.Nullable;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.YearMonth;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 商家订单流水业务层实现
 *
 * @author Chopper
 * @since 2020/11/17 7:38 下午
 */
@Slf4j
@Service
@RequiredArgsConstructor(onConstructor_= @Lazy)
public class OrderFlowServiceImpl extends ServiceImpl<OrderFlowMapper, OrderFlow> implements OrderFlowService {


    private final OrderItemFlowService orderItemFlowService;

    private final FlowReviewLogService flowReviewLogService;


    private final PaymentClient paymentClient;

    private final StoreClient storeClient;

    private final PayApi payApi;

    private final UserClient userClient;

    private final SettingClient settingClient;
    private final ReturnActivityClient returnActivityClient;
    private final GreenClient greenClient;
    private final GreenCommonwealContributionClient greenCommonwealContributionClient;

    private final UserApi userApi;
    private final DistributionClient distributionClient;
    private final DictionaryClient dictionaryClient;
    private final ThreadConfig threadConfig;
    private final OrderItemService orderItemService;
    private final GoodsSkuClient goodsSkuClient;
    private final IRankingActivityConfigService activityConfigService;
    private final IRankingScoreDetailsService scoreDetailsService;
    private final IRankingDistributionService rankingDistributionService;
    private final OrderService orderService;
    private final OrderMapper orderMapper;
    private final IPaymentCallbackOrderLogService paymentCallbackOrderLogService;
    private final OrderFlowProfitSharingErrorService orderFlowProfitSharingErrorService;
    private final OperationCenterClient operationCenterClient;
    private final UnionClient unionClient;


    @Override
    @Transactional
    public void payOrder(Order order, List<OrderItem> orderItems) {
        //检查订单流水是否存在
        if(getByOrderSn(order.getSn()) != null){
            throw new ServiceException("订单流水已存在");
        }
        OrderFlow orderFlow = new OrderFlow(order);

        //添加付款交易流水
        boolean flag1 = this.save(orderFlow);
        // 执行异步保存日志方法 2024-02-21
        Objects.requireNonNull(threadConfig.getAsyncExecutor()).execute(() -> {
            //记录支付回调方法,执行日志OrerServiceImpl.payOrder.updateId
            PaymentCallbackOrderLog callbackOrderLog = new PaymentCallbackOrderLog();
            callbackOrderLog.setOutTradeOn(order.getOutTradeNo());
            callbackOrderLog.setOrderSn(order.getSn());
            callbackOrderLog.setTransactionId(order.getTransactionId());
            callbackOrderLog.setMethodName("OrerFlowServiceImpl.payOrder.save()");
            callbackOrderLog.setParams(JSONObject.toJSONString(orderFlow));
            callbackOrderLog.setExecResult("" + flag1);
            paymentCallbackOrderLogService.save(callbackOrderLog);
        });
        boolean flag = orderItemFlowService.generateOrderItemFlow(orderItems, orderFlow);

        Objects.requireNonNull(threadConfig.getAsyncExecutor()).execute(() -> {
            //记录支付回调方法,执行日志OrerServiceImpl.payOrder.updateId
            PaymentCallbackOrderLog callbackOrderLog = new PaymentCallbackOrderLog();
            callbackOrderLog.setOutTradeOn(order.getOutTradeNo());
            callbackOrderLog.setOrderSn(order.getSn());
            callbackOrderLog.setTransactionId(order.getTransactionId());
            callbackOrderLog.setMethodName("OrerFlowServiceImpl.orderItemFlowService.generateOrderItemFlow()");
            JSONArray jsonArray = new JSONArray();
            jsonArray.add(JSONObject.toJSONString(orderItems));
            jsonArray.add(JSONObject.toJSONString(orderFlow));
            callbackOrderLog.setParams(jsonArray.toJSONString());
            callbackOrderLog.setExecResult("" + flag);
            paymentCallbackOrderLogService.save(callbackOrderLog);
        });
        // 绿色贡献值计算
        initGreen(orderFlow);

        //如果存在异常数据，则对记录进行处理
        checkIsError(orderFlow);

    }

    /**
     * 绿色贡献值计算
     * @param orderFlow 订单流水
     * */
    public void initGreen(OrderFlow orderFlow){
        log.info("绿色贡献值计算-->>{}",orderFlow);
        //城市代理
        if(orderFlow.getSiteGreenScore()>0){
            User user = userClient.getById(orderFlow.getUrbanIdBySupplier());
            if(user != null) {
                GreenContributionInfo greenContributionInfo = new GreenContributionInfo();
                greenContributionInfo.initGreenContributionInfoSettled(user, orderFlow.getOrderSn(), orderFlow.getSiteGreenScore());
                greenContributionInfo.setUserType(SceneEnums.URBAN_SUBSTATION.name());
                greenClient.saveSettle(greenContributionInfo);
            }
        }
        //城市站点ID-订单地址
        if(orderFlow.getSiteAddressGreenScore()>0){
            User user = userClient.getById(orderFlow.getUrbanIdByAddress());
            if(user != null){
                GreenContributionInfo greenContributionInfo = new GreenContributionInfo();
                greenContributionInfo.initGreenContributionInfoSettled(user,orderFlow.getOrderSn(),orderFlow.getSiteAddressGreenScore());
                greenContributionInfo.setUserType(SceneEnums.URBAN_SUBSTATION_ADDRESS.name());
                greenClient.saveSettle(greenContributionInfo);
            }
        }
        //上推佣金（店主-下级用户订单分佣）
        if(orderFlow.getLowerCommiss() > 0){
            User user = userClient.getById(orderFlow.getLowerCommissId());
            if(user != null) {
                GreenContributionInfo greenContributionInfo = new GreenContributionInfo();
                greenContributionInfo.initGreenContributionInfoSettled(user, orderFlow.getOrderSn(), orderFlow.getLowerCommiss());
                greenContributionInfo.setUserType(SceneEnums.LOWER.name());
                greenClient.saveSettle(greenContributionInfo);
            }
        }
        //间推佣金（店主-间推用户订单分佣）
        if(orderFlow.getLowerSubCommiss() > 0){
            User user = userClient.getById(orderFlow.getLowerSubCommissId());
            if(user != null) {
                GreenContributionInfo greenContributionInfo = new GreenContributionInfo();
                //构造内增加user判空判断
                greenContributionInfo.initGreenContributionInfoSettled(user, orderFlow.getOrderSn(), orderFlow.getLowerSubCommiss());
                greenContributionInfo.setUserType(SceneEnums.LOWERSUB.name());
                greenClient.saveSettle(greenContributionInfo);
            }
        }
        //商家
        if(orderFlow.getStoreGreenScore()>0){
            User user = userClient.getByExtId(orderFlow.getStoreId());
            if(user != null) {
                GreenContributionInfo greenContributionInfo = new GreenContributionInfo();
                greenContributionInfo.initGreenContributionInfoSettled(user, orderFlow.getOrderSn(), orderFlow.getStoreGreenScore());
                greenContributionInfo.setUserType(SceneEnums.STORE.name());
                greenClient.saveSettle(greenContributionInfo);
            }
        }
        //用户
        if(orderFlow.getMemberGreenScore() > 0){
            User user = userClient.getById(orderFlow.getMemberId());
            if(user != null) {
                GreenContributionInfo greenContributionInfo = new GreenContributionInfo();
                greenContributionInfo.initGreenContributionInfoSettled(user, orderFlow.getOrderSn(), orderFlow.getMemberGreenScore());
                greenContributionInfo.setUserType(SceneEnums.MEMBER.name());
                greenClient.saveSettle(greenContributionInfo);
            }
        }
        //分销员
        if(orderFlow.getDistributionSettlementPrice()>0){
            User user = userClient.getById(orderFlow.getDistributionId());
            if(user != null) {
                GreenContributionInfo greenContributionInfo = new GreenContributionInfo();
                greenContributionInfo.initGreenContributionInfoSettled(user, orderFlow.getOrderSn(), orderFlow.getDistributionSettlementPrice());
                greenContributionInfo.setUserType(SceneEnums.DISTRIBUTION.name());
                greenClient.saveSettle(greenContributionInfo);
            }
        }
        //代理
        if(orderFlow.getSupplierGreenScore()>0){
            User user = userClient.getByExtId2(orderFlow.getSupplierId());
            if(user != null) {
                GreenContributionInfo greenContributionInfo = new GreenContributionInfo();
                greenContributionInfo.initGreenContributionInfoSettled(user, orderFlow.getOrderSn(), orderFlow.getSupplierGreenScore());
                greenContributionInfo.setUserType(SceneEnums.SUPPLIER.name());
                greenClient.saveSettle(greenContributionInfo);
            }
        }
        //工会-运营中心
        if(orderFlow.getUnionGreenScore() > 0){
            Order order = orderService.getBySn(orderFlow.getOrderSn());
            if (null != order) {
                String[] address = order.getConsigneeAddressIdPath().split(",");
                List<Union> unionList = unionClient.getListByFiled("city_id", address[1]);
                if (!unionList.isEmpty()) {
                    OperationCenter operationCenter = operationCenterClient.getByAddressId(unionList.get(0).getProvinceId());
                    if (null != operationCenter) {
                        User user = userClient.getById(operationCenter.getUserId());
                        GreenContributionInfo greenContributionInfo = new GreenContributionInfo();
                        greenContributionInfo.initGreenContributionInfoSettled(user, orderFlow.getOrderSn(), orderFlow.getUnionGreenScore());
                        greenContributionInfo.setUserType(SceneEnums.OPERATION_CENTER.name());
                        greenContributionInfo.setUnionId(unionList.get(0).getId());
                        greenClient.saveSettle(greenContributionInfo);
                    }
                }
            }
        }
    }


    @Override
    public void refundOrder(RefundFlow refundFlow) {

        OrderFlow orderFlow = getByOrderSn(refundFlow.getOrderSn());
        orderFlow.appendRefundPrice(refundFlow.getRefundPrice());

        if (Boolean.TRUE.equals(orderFlow.getFullRefund())) {
            orderFlow.setProfitSharing(ProfitSharingStatusEnum.ORDER_CANCEL.name());
        }
        //f分退款
//        orderFlow.getMemberId();
//        User user = userClient.getById(orderFlow.getMemberId());
//        if (orderFlow.getFmoney() != null && orderFlow.getFmoney() > 0D && user != null && StringUtils.isNotBlank(user.getOpenId())) {
//            int fmoney = new BigInteger(String.valueOf((long) (orderFlow.getFmoney() * 100))).intValue();
//            boolean payment = payApi.gMoneyPayment(user.getOpenId(), "商品退款退款F分", fmoney, 0, 2, 3);
//            if (!payment) {
//                throw new ServiceException("服务异常，用户提现失败");
//            }
//        }
        this.updateById(orderFlow);
    }

    @Override
    @Transactional
    public void refundOrder(RefundFlow refundFlow, AfterSale afterSale) {

        OrderFlow orderFlow = getByOrderSn(refundFlow.getOrderSn());

        OrderItemFlow orderItemFlow = orderItemFlowService.getByOrderSnAndSkuId(refundFlow.getOrderSn(), afterSale.getSkuId());

        CurrentRefundPriceDTO currentRefundPriceDTO = orderItemFlow.refund(afterSale);

        orderFlow.appendRefundPrice(currentRefundPriceDTO);

        orderItemFlowService.updateById(orderItemFlow);

        this.updateById(orderFlow);
    }

    /**
     * 根据流水创建异常审核记录
     *
     * @param orderFlow 订单流水
     */
    private void checkIsError(OrderFlow orderFlow) {

        List<FlowReviewLog> flowReviewLogs = new ArrayList<>();
        //如果订单流水中存在负数，需要人工审核
        if (Boolean.FALSE.equals(orderFlow.getPlatformVerify())) {
            flowReviewLogs.add(FlowReviewLog.builder()
                    .orderSn(orderFlow.getOrderSn())
                    .orderFlowSn(orderFlow.getSn())
                    .operatorType(SceneEnums.SYSTEM.name())
                    .operatorId("0")
                    .operatorName("系统")
                    .message("系统审核，订单存在异常流水记录，平台在该次交易中出现负数，需要手动审核处理之后订单才能继续进行")
                    .build());

        }
        if (Boolean.FALSE.equals(orderFlow.getSupplierVerify())) {
            flowReviewLogs.add(FlowReviewLog.builder()
                    .orderSn(orderFlow.getOrderSn())
                    .orderFlowSn(orderFlow.getSn())
                    .operatorType(SceneEnums.SYSTEM.name())
                    .operatorId("0")
                    .operatorName("系统")
                    .message("系统审核，订单存在异常流水记录，供应商在该次交易中出现负数，需要手动审核处理之后订单才能继续进行")
                    .build());
        }
        if (Boolean.FALSE.equals(orderFlow.getStoreVerify())) {
            flowReviewLogs.add(FlowReviewLog.builder()
                    .orderSn(orderFlow.getOrderSn())
                    .orderFlowSn(orderFlow.getSn())
                    .operatorType(SceneEnums.SYSTEM.name())
                    .operatorId("0")
                    .operatorName("系统")
                    .message("系统审核，订单存在异常流水记录，店铺在该次交易中出现负数，需要手动审核处理之后订单才能继续进行")
                    .build());
        }
        if (Boolean.FALSE.equals(orderFlow.getUrbanVerify())) {
            flowReviewLogs.add(FlowReviewLog.builder()
                    .orderSn(orderFlow.getOrderSn())
                    .orderFlowSn(orderFlow.getSn())
                    .operatorType(SceneEnums.SYSTEM.name())
                    .operatorId("0")
                    .operatorName("系统")
                    .message("系统审核，订单存在异常流水记录，供应商在该次交易中出现负数，需要手动审核处理之后订单才能继续进行")
                    .build());
        }
        flowReviewLogService.saveBatch(flowReviewLogs);
    }

    @Override
    public Page<OrderFlow> orderFlowPage(OrderFlowQueryDTO orderFlowQueryDTO) {
        if (SceneEnums.URBAN_SUBSTATION.equals(Objects.requireNonNull(UserContext.getCurrentUser()).getScene())) {
            List<Store> storeList = storeClient.getSupplierListByUrbanId(UserContext.getCurrentUser().getId());
            if (!storeList.isEmpty()) {
                List<String> ids = storeList.stream().map(Store::getId).toList();
                orderFlowQueryDTO.setStoreIds(ids);
            }
        }
        return this.page(PageUtil.initPage(orderFlowQueryDTO), orderFlowQueryDTO.generatorQueryWrapper());
    }

    @Override
    public OrderFlow queryOne(OrderFlowQueryDTO orderFlowQueryDTO) {
        return this.getOne(orderFlowQueryDTO.generatorQueryWrapper());
    }

    @Override
    public List<StoreFlowPayDownloadVO> getStoreFlowPayDownloadVO(OrderFlowQueryDTO orderFlowQueryDTO) {
        return baseMapper.getStoreFlowPayDownloadVO(orderFlowQueryDTO.generatorQueryWrapper());
    }

    @Override
    public List<OrderFlow> listStoreFlow(OrderFlowQueryDTO orderFlowQueryDTO) {
        return this.list(orderFlowQueryDTO.generatorQueryWrapper());
    }

    @Override
    public boolean verifyOrderFlow(String id, String verifyStatus, String scene) {
        LambdaUpdateWrapper<OrderFlow> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(OrderFlow::getId, id);
        if (SceneEnums.SUPPLIER.name().equals(scene)) {
            updateWrapper.set(OrderFlow::getSupplierVerify, verifyStatus);
        } else if (SceneEnums.STORE.name().equals(scene)) {
            updateWrapper.set(OrderFlow::getStoreVerify, verifyStatus);
        } else if (SceneEnums.MANAGER.name().equals(scene)) {
            updateWrapper.set(OrderFlow::getPlatformVerify, verifyStatus);
        } else if (SceneEnums.URBAN_SUBSTATION.name().equals(scene)) {
            updateWrapper.set(OrderFlow::getUrbanVerify, verifyStatus);
        }
        return this.update(updateWrapper);
    }

    @Override
    public OrderFlow orderFlowDetail(String id) {
        QueryWrapper<OrderFlow> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);

        switch (UserContext.getCurrentUser().getScene()) {
            case STORE -> queryWrapper.eq("store_id", UserContext.getCurrentUser().getExtendId());
            case SUPPLIER -> queryWrapper.eq("supplier_id", UserContext.getCurrentUser().getExtendId());
            case MEMBER -> queryWrapper.eq("distributor_id", UserContext.getCurrentUser().getExtendId());
            case URBAN_SUBSTATION -> {
                List<Store> storeList = storeClient.getSupplierListByUrbanId(UserContext.getCurrentUser().getId());
                if (!storeList.isEmpty()) {
                    List<String> ids = storeList.stream().map(Store::getId).toList();
                    queryWrapper.in("supplier_id", ids);
                }else {
                    queryWrapper.eq("supplier_id", "");
                }
            }
            default -> {
                break;
            }

        }
        return this.getOne(queryWrapper);
    }


    @Override
    public Page<OrderFlow> waitVerify(PageVO pageVO, String orderSn, String orderFlowStatus) {

        QueryWrapper<OrderFlow> queryWrapper = new QueryWrapper<>();

        queryWrapper.eq(StringUtils.isNotEmpty(orderSn), "order_sn", orderSn);

        queryWrapper.eq(StringUtils.isNotEmpty(orderFlowStatus), "order_flow_status", orderFlowStatus);

        switch (UserContext.getCurrentUser().getScene()) {
            case STORE -> queryWrapper.eq("store_id", UserContext.getCurrentUser().getExtendId());
            case SUPPLIER -> queryWrapper.eq("supplier_id", UserContext.getCurrentUser().getExtendId());
            case MEMBER -> queryWrapper.eq("distributor_id", UserContext.getCurrentUser().getExtendId());
            case URBAN_SUBSTATION -> {
                List<Store> storeList = storeClient.getSupplierListByUrbanId(UserContext.getCurrentUser().getId());
                if (!storeList.isEmpty()) {
                    List<String> ids = storeList.stream().map(Store::getId).toList();
                    queryWrapper.in("supplier_id", ids);
                }else {
                    queryWrapper.eq("supplier_id", "");
                }

            }
            default -> {
                break;
            }
        }
        Page<OrderFlow> page = this.page(PageUtil.initPage(pageVO), queryWrapper);
        if (SceneEnums.URBAN_SUBSTATION.equals(UserContext.getCurrentUser().getScene())) {
            if (!page.getRecords().isEmpty()) {
                page.getRecords().stream().forEach(orderFlow -> {
                    if (orderFlow.getUrbanIdBySupplier().equals(UserContext.getCurrentUser().getId())) {
                        orderFlow.setApplyFlag(true);
                    }else {
                        orderFlow.setApplyFlag(false);
                    }
                });
            }
        }
        return page;

    }

    @Override
    public List<OrderFlow> listByOrderSn(String orderSn) {

        QueryWrapper<OrderFlow> queryWrapper = new QueryWrapper<>();

        queryWrapper.eq("order_sn", orderSn);

        queryHandler(queryWrapper);
        return this.list(queryWrapper);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    @ShardingTransactionType(TransactionType.BASE)
    public void pass(String id) {
        //查询指定流水
        QueryWrapper<OrderFlow> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);

        queryHandler(queryWrapper);
        OrderFlow orderFlow = this.getOne(queryWrapper);
        if (orderFlow == null) {
            throw new ServiceException(ResultCode.ORDER_FLOW_NOT_EXIST);
        }
        //流水审核状态判定
        switch (UserContext.getCurrentUser().getScene()) {
            case STORE -> {
                if (orderFlow.getStoreVerify() != null && orderFlow.getStoreVerify()) {
                    throw new ServiceException(ResultCode.ORDER_FLOW_NEED_NOT_VERIFY);
                }
            }
            case SUPPLIER -> {
                if (orderFlow.getSupplierVerify() != null && orderFlow.getSupplierVerify()) {
                    throw new ServiceException(ResultCode.ORDER_FLOW_NEED_NOT_VERIFY);
                }
            }
            case MANAGER -> {
                if (orderFlow.getPlatformVerify() != null && orderFlow.getPlatformVerify()) {
                    throw new ServiceException(ResultCode.ORDER_FLOW_NEED_NOT_VERIFY);
                }
            }
            case URBAN_SUBSTATION -> {
                if (orderFlow.getUrbanVerify() != null && orderFlow.getUrbanVerify()) {
                    throw new ServiceException(ResultCode.ORDER_FLOW_NEED_NOT_VERIFY);
                }
            }
            default -> {
                break;
            }
        }

        //批量审核
        LambdaUpdateWrapper<OrderFlow> updateWrapper = new LambdaUpdateWrapper<>();
        switch (UserContext.getCurrentUser().getScene()) {
            case STORE -> {
                updateWrapper.eq(OrderFlow::getStoreId, UserContext.getCurrentUser().getExtendId());
                updateWrapper.set(OrderFlow::getStoreVerify, true);
                if (orderFlow.getSellerSettlementPrice() >= 0) {
                    throw new ServiceException(ResultCode.ORDER_FLOW_ERROR);
                }
                PaymentSubsidies paymentSubsidies = subsidies(orderFlow.getOrderSn(), -orderFlow.getSellerSettlementPrice(),
                        UserContext.getCurrentUser().getExtendId(),
                        SceneEnums.STORE.getDescription() + "_" + UserContext.getCurrentUser().getNickName());
                updateWrapper.set(OrderFlow::getStoreOutTradeNo, paymentSubsidies.getOutTradeNo());

                orderFlow.setStoreVerify(true);

            }
            case SUPPLIER -> {
                updateWrapper.eq(OrderFlow::getSupplierId, UserContext.getCurrentUser().getExtendId());
                updateWrapper.set(OrderFlow::getSupplierId, true);
                if (orderFlow.getSupplierSettlementPrice() >= 0) {
                    throw new ServiceException(ResultCode.ORDER_FLOW_ERROR);
                }
                PaymentSubsidies paymentSubsidies = subsidies(orderFlow.getOrderSn(), -orderFlow.getSupplierSettlementPrice(),
                        UserContext.getCurrentUser().getExtendId(),
                        SceneEnums.SUPPLIER.getDescription() + "_" + UserContext.getCurrentUser().getNickName());
                updateWrapper.set(OrderFlow::getSupplierOutTradeNo, paymentSubsidies.getOutTradeNo());

                orderFlow.setSupplierVerify(true);
            }
            case MANAGER -> {
                updateWrapper.set(OrderFlow::getPlatformVerify, true);
                if (orderFlow.getPlatformSettlementPrice() >= 0) {
                    throw new ServiceException(ResultCode.ORDER_FLOW_ERROR);
                }
                PaymentSubsidies paymentSubsidies = subsidies(orderFlow.getOrderSn(), -orderFlow.getPlatformSettlementPrice(),
                        UserContext.getCurrentUser().getExtendId(), "平台" + "_" + UserContext.getCurrentUser().getNickName());
                updateWrapper.set(OrderFlow::getPlatformOutTradeNo, paymentSubsidies.getOutTradeNo());

                orderFlow.setPlatformVerify(true);
            }
            case URBAN_SUBSTATION -> {
                updateWrapper.eq(OrderFlow::getUrbanIdBySupplier, UserContext.getCurrentUser().getExtendId());
                updateWrapper.set(OrderFlow::getUrbanVerify, true);
                if (orderFlow.getSupplierSettlementPrice() >= 0) {
                    throw new ServiceException(ResultCode.ORDER_FLOW_ERROR);
                }
                PaymentSubsidies paymentSubsidies = subsidies(orderFlow.getOrderSn(), -orderFlow.getSupplierSettlementPrice(),
                        UserContext.getCurrentUser().getExtendId(),
                        SceneEnums.URBAN_SUBSTATION.getDescription() + "_" + UserContext.getCurrentUser().getNickName());
                updateWrapper.set(OrderFlow::getSupplierOutTradeNo, paymentSubsidies.getOutTradeNo());

                orderFlow.setUrbanVerify(true);
            }
            default -> {
                return;
            }
        }

        if (orderFlow.getSupplierVerify() && orderFlow.getStoreVerify() && orderFlow.getUrbanVerify() && Boolean.TRUE.equals(orderFlow.getPlatformVerify())) {
            updateWrapper.set(OrderFlow::getOrderFlowStatus, OrderFlowStatusEnum.PASS.name());
        }

        updateWrapper.eq(OrderFlow::getId, id);

        //记录日志
        flowReviewLogService.save(FlowReviewLog.builder()
                .operatorType(UserContext.getCurrentUser().getScene().name())
                .operatorId(UserContext.getCurrentUser().getExtendId())
                .operatorName(UserContext.getCurrentUser().getUsername())
                .orderFlowSn(orderFlow.getSn())
                .orderSn(orderFlow.getOrderSn())
                .message("流水单号[" + orderFlow.getSn() + "]，关联订单[" + orderFlow.getOrderSn() + "]，审核通过")
                .build());


        this.update(updateWrapper);
    }

    /**
     * 补差价接口调用
     *
     * @param orderSn        订单号
     * @param subsidiesPrice 差额
     * @return 支付流水
     */
    private PaymentSubsidies subsidies(String orderSn, Double subsidiesPrice, String userId, String nickName) {
        return paymentClient.subsidies(
                SubsidiesParams.builder()
                        .orderSn(orderSn)
                        .payerId(userId)
                        .nickname(nickName)
                        .paymentMethodEnum(PaymentMethodEnum.WALLET)
                        .price(subsidiesPrice)
                        .build()
        );
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public OrderFlow refuse(String id) {

        //查询指定流水
        QueryWrapper<OrderFlow> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);
        queryHandler(queryWrapper);
        OrderFlow orderFlow = this.getOne(queryWrapper);

        SceneHelp.objectHandler(orderFlow);

        orderFlow.setOrderFlowStatus(OrderFlowStatusEnum.REFUSE.name());

        this.updateById(orderFlow);
        //记录日志
        flowReviewLogService.save(FlowReviewLog.builder()
                .operatorType(UserContext.getCurrentUser().getScene().name())
                .operatorId(UserContext.getCurrentUser().getExtendId())
                .operatorName(UserContext.getCurrentUser().getUsername())
                .orderFlowSn(orderFlow.getSn())
                .orderSn(orderFlow.getOrderSn())
                .message("流水单号[" + orderFlow.getSn() + "]，关联订单[" + orderFlow.getOrderSn() + "]，" +
                        UserContext.getCurrentUser().getScene().getDescription() + "[" + UserContext.getCurrentUser().getNickName() + "]审核拒绝")
                .build());
        return orderFlow;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void force(String orderSn) {
        if (Objects.requireNonNull(UserContext.getCurrentUser()).getScene().equals(SceneEnums.MANAGER)) {
            List<OrderFlow> orderFlowList = this.listByOrderSn(orderSn);
            orderFlowList.forEach(orderFlow -> {
                orderFlow.setPlatformVerify(true);
                orderFlow.setSupplierVerify(true);
                orderFlow.setStoreVerify(true);
                orderFlow.setUrbanVerify(true);
                orderFlow.setOrderFlowStatus(OrderFlowStatusEnum.FORCE_PASS.name());
            });
            this.updateBatchById(orderFlowList);

            //记录日志
            flowReviewLogService.save(FlowReviewLog.builder()
                    .message("平台强制审核通过订单[" + orderSn + "]相关流水")
                    .orderFlowSn(orderFlowList.stream().map(OrderFlow::getSn).collect(Collectors.joining(",")))
                    .orderSn(orderSn)
                    .operatorName(UserContext.getCurrentUser().getUsername())
                    .operatorId(UserContext.getCurrentUser().getExtendId())
                    .operatorType(UserContext.getCurrentUser().getScene().name())
                    .build());
        }
    }

    @Override
    public OrderFlow getByOrderSn(String sn) {
        return this.getOne(new LambdaQueryWrapper<OrderFlow>()
                .eq(OrderFlow::getOrderSn, sn).last("limit 1"));
    }


    @Override
    public List<OrderFlow> waitProfitSharingFlows() {
        //获取所有待分账的订单
        LambdaQueryWrapper<OrderFlow> lambdaQueryWrapper = Wrappers.lambdaQuery();
        lambdaQueryWrapper.eq(OrderFlow::getProfitSharing, ProfitSharingStatusEnum.PROCESSING.name());
        return this.list(lambdaQueryWrapper);
    }

    @Override
    public void updateProfitSharingStatus() {
        baseMapper.updateProfitSharingStatus();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void profitSharingOrderFlow(OrderFlow orderFlow) {
        log.info("---开始");
        try {
            //分账
            OutOrderLogVO outOrderLogVO = paymentClient.profitSharing(new ProfitSharingRequestDTO(orderFlow));

            //更新分账状态
            LambdaUpdateWrapper<OrderFlow> updateWrapper = Wrappers.lambdaUpdate();

            switch (OutOrderLogStatusEnums.valueOf(outOrderLogVO.getOutOrderLog().getStatus())) {
                case FINISHED -> {
                    updateWrapper.set(OrderFlow::getProfitSharing, ProfitSharingStatusEnum.FINISHED.name());
                    //分账成功，更新全返卷生效状态
                    returnActivityClient.updateStatus(orderFlow.getMemberId(),orderFlow.getOrderSn(),null);

                    try {
                        // 绿色公益打款
                        if (null != orderFlow.getGreenCommonwealGreenScore() &&
                                orderFlow.getGreenCommonwealGreenScore() > 0) {
                            log.info("=======绿色公益打款========", orderFlow.getGreenCommonwealGreenScore());
                            addCommonweal(orderFlow);
                        }
                    }catch (Exception e) {
                        log.error("绿色公益打款异常：{}", e.getMessage());
                    }

                }
                case FAIL -> {

                    updateWrapper.set(OrderFlow::getProfitSharing, ProfitSharingStatusEnum.FAIL.name());

                    updateWrapper.set(OrderFlow::getErrorMsg,
                            outOrderLogVO.getOutOrderDetailLogList().stream().map(OutOrderDetailLog::getFailReason).collect(Collectors.joining(",")));
                }
                case PROCESSING -> {
                    return;
                }
            }
            //    * FINISHED：分账完成
            updateWrapper.eq(OrderFlow::getId, orderFlow.getId());
            this.update(updateWrapper);

            //进行判断当前用户是否有上级，并且上级是分销员。有则添加积分变动记录，与变动佣金
            Objects.requireNonNull(threadConfig.getAsyncExecutor()).execute(()->{
                log.info("进行判断当前用户是否有上级，并且上级是分销员-----");
                User user = userClient.getById(orderFlow.getMemberId());
                String parentOpenId = userApi.getParent(user.getOpenId());
                if (cn.lili.common.utils.StringUtils.isEmpty(parentOpenId)) {
                    return;
                }
                User memberUser = userClient.getByOpenId(parentOpenId, SceneEnums.MEMBER.name());
                if (memberUser == null || cn.lili.common.utils.StringUtils.isEmpty(memberUser.getId())) {
                    return;
                }
//                Distribution distribution = distributionClient.getDistribution(memberUser.getId());
                RankingDistribution distribution = rankingDistributionService.getRankingDistributionByMemberId(memberUser.getId());
                if (distribution == null || cn.lili.common.utils.StringUtils.isEmpty(distribution.getId()) || !DistributionStatusEnum.PASS.name().equals(distribution.getDistributionStatus())) {
                    return;
                }
                List<OrderItem> orderItems = orderItemService.list(new LambdaQueryWrapper<OrderItem>().eq(OrderItem::getOrderSn, orderFlow.getOrderSn()));
                //上级是分销员 ==》 生成积分记录并给上级分销员增加积分总额
                for (OrderItem orderItem : orderItems) {
                    GoodsSku goodsSku = goodsSkuClient.getGoodsSkuById(orderItem.getSkuId());
                    //积分业绩
                    if(!(goodsSku.getGreenScore() != null && goodsSku.getGreenScore() > 0)) {
                        return;
                    }
                    JSONObject jsonObject = JSONObject.parseObject(settingClient.get(SettingEnum.GREEN_GOODS.name()).getSettingValue());
                    Integer distributionProportion = jsonObject.getInteger("distributionProportion");
                    double score = CurrencyUtil.mul(CurrencyUtil.div(CurrencyUtil.mul(goodsSku.getGreenScore(), distributionProportion == null ? 0 : distributionProportion), 100), orderItem.getNum());

                    LambdaUpdateWrapper<RankingScoreDetails> detailsLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
                    detailsLambdaUpdateWrapper.eq(RankingScoreDetails::getParentUserId, memberUser.getId());
                    detailsLambdaUpdateWrapper.eq(RankingScoreDetails::getBuyerUserId, user.getId());
                    detailsLambdaUpdateWrapper.eq(RankingScoreDetails::getOrderSn, orderItem.getSn());
                    detailsLambdaUpdateWrapper.set(RankingScoreDetails::getOrderStatus, DictConstant.SCORE_ORDER_STATUS_02);
                    scoreDetailsService.update(detailsLambdaUpdateWrapper);

                    //添加佣金总额
                    //distributionClient.addRebateTotal(distribution.getId(), BigDecimal.valueOf(score));
                    RankingDistribution param = new RankingDistribution();
                    param.setId(distribution.getId());
                    param.setRebateTotal(new BigDecimal(score));
                    rankingDistributionService.updateRankingDistribution(param);
                }
            });

        } catch (Exception se) {
            orderFlow.setErrorMsg(se.getMessage());
            orderFlow.setProfitSharing(ProfitSharingStatusEnum.FINISHED.name());
            super.updateById(orderFlow);

            OrderFlowProfitSharingError orderFlowProfitSharingError = new OrderFlowProfitSharingError();
            orderFlowProfitSharingError.setErrorMessage(se.getMessage());
            orderFlowProfitSharingError.setSn(orderFlow.getOrderSn());
            orderFlowProfitSharingErrorService.save(orderFlowProfitSharingError);
            log.error("分账失败，订单流水信息：{}", orderFlow, se);
            log.error("se == {}", se.getMessage());
        }
    }

    @Nullable
    private void addCommonweal(OrderFlow orderFlow) {
        // 获取服务接口
        //Setting setting = settingClient.get("GREEN_COMMONWEAL_SERVICE");
        // 获取用户openId
        User user = userClient.getById(orderFlow.getMemberId());
        if (null != user && CharSequenceUtil.isNotEmpty(user.getOpenId())) {
            // 调用绿色公益服务接口
            GreenCommonwealContribution contribution = new GreenCommonwealContribution();
            contribution.setUserId(user.getId());
            contribution.setOpenId(user.getOpenId());
            contribution.setOrderNo(orderFlow.getOrderSn());
            contribution.setUserName(user.getUsername());
            contribution.setRemarks("用户" + user.getUsername() + "【" + user.getId() + "】,购买商品订单号：" + orderFlow.getOrderSn() + "，赠加公益资金：" + orderFlow.getGreenCommonwealGreenScore());
            contribution.setContributionMoney(new BigDecimal(orderFlow.getGreenCommonwealGreenScore()));
            greenCommonwealContributionClient.contribution(contribution);
            /*
            Map<String, Object> params = new HashMap<>();
            params.put("openId", user.getOpenId());
            params.put("orderNo", orderFlow.getOrderSn());
            params.put("contributionMoney", orderFlow.getGreenCommonwealGreenScore());
            log.info("绿色公益打款参数：" + JSONObject.toJSONString(params));
            *//*HttpRequest request = HttpUtil.createPost(setting.getSettingValue() + "openApp/v1/other/add")
                    .body(JSONObject.toJSONString(params));*//*
            String result = HttpUtil.post( "http://service-shop-gateway.test.local.chainlettre05.com/openApp/v1/other/add", params);
            JSONObject jsonObject = JSONObject.parseObject(result);
            if (jsonObject.getInteger("code") == 200) {
                log.info("调用绿色公益服务成功");
            }else {
                log.info("调用绿色公益服务失败：" + jsonObject.getString("msg"));
            }*/
        }
    }


    /**
     * 生成查询条件
     *
     * @param queryWrapper 查询条件
     */
    private void queryHandler(QueryWrapper queryWrapper) {
        if (UserContext.getCurrentUser() != null) {
            switch (UserContext.getCurrentUser().getScene()) {
                case STORE -> queryWrapper.eq("store_id", UserContext.getCurrentUser().getExtendId());
                case SUPPLIER -> queryWrapper.eq("supplier_id", UserContext.getCurrentUser().getExtendId());
                case MEMBER -> queryWrapper.eq("distributor_id", UserContext.getCurrentUser().getExtendId());
                case URBAN_SUBSTATION -> {
                    List<Store> storeList = storeClient.getSupplierListByUrbanId(UserContext.getCurrentUser().getId());
                    if (!storeList.isEmpty()) {
                        List<String> ids = storeList.stream().map(Store::getId).toList();
                        queryWrapper.in("supplier_id", ids);
                    }else {
                        queryWrapper.eq("supplier_id", "");
                    }

                }
                default -> {
                }
            }
        }
    }

    public OrderFlow getSumByOrderSn (String orderSn) {
        return this.baseMapper.getSumByOrderSn(orderSn);
    }

    /**
     * 我的收益
     */
    @Override
    public MyEarningsVO myEarnings() {
        MyEarningsVO result = new MyEarningsVO();
        BigDecimal defaultValue = BigDecimal.valueOf(0);
        result.setDateTotalMoney(defaultValue);
        result.setTotalMoney(defaultValue);
        result.setWaitForSettlementMoney(defaultValue);

//        String string = userClient.callGetSubordinatesAndSubSubordinates(UserContext.getCurrentId());
//        if (StringUtils.isEmpty(string)) {
//            return result;
//        }
        LambdaQueryWrapper<OrderFlow> orderFlowLambdaQueryWrapper = new LambdaQueryWrapper<>();
        orderFlowLambdaQueryWrapper.in(OrderFlow::getProfitSharing, ProfitSharingStatusEnum.FINISHED.name(), ProfitSharingStatusEnum.PROCESSING.name(), ProfitSharingStatusEnum.WAIT_COMPLETE.name());
//        orderFlowLambdaQueryWrapper.in(OrderFlow::getMemberId, (Object[]) string.split(","));
        orderFlowLambdaQueryWrapper.and(q -> q.eq(OrderFlow::getLowerCommissId, UserContext.getCurrentId()).or().eq(OrderFlow::getLowerSubCommissId, UserContext.getCurrentId()));
        orderFlowLambdaQueryWrapper.select(OrderFlow::getId, OrderFlow::getLowerCommiss, OrderFlow::getProfitSharing, OrderFlow::getLowerSubCommiss, OrderFlow::getFlowPrice, OrderFlow::getCreateTime, OrderFlow::getLowerCommissId);
        List<OrderFlow> orderFlows = super.list(orderFlowLambdaQueryWrapper);

        //完成结算的金额
        double finishedMoney = orderFlows.stream().filter(f -> ProfitSharingStatusEnum.FINISHED.name().equals(f.getProfitSharing())).mapToDouble(flow ->  StringUtils.isNotBlank(flow.getLowerCommissId()) && flow.getLowerCommissId().equals(UserContext.getCurrentId()) ? flow.getLowerCommiss() : flow.getLowerSubCommiss()).sum();
        //待结算的金额
        double waitCompleteMoney = orderFlows.stream().filter(f -> ProfitSharingStatusEnum.PROCESSING.name().equals(f.getProfitSharing()) || ProfitSharingStatusEnum.WAIT_COMPLETE.name().equals(f.getProfitSharing())).mapToDouble(flow ->  StringUtils.isNotBlank(flow.getLowerCommissId()) && flow.getLowerCommissId().equals(UserContext.getCurrentId()) ? flow.getLowerCommiss() : flow.getLowerSubCommiss()).sum();
        //查询已结算的且本月的
        LocalDate currentDate = LocalDate.now();
        double currentMonthMoney = orderFlows.stream()
                .filter(f -> ProfitSharingStatusEnum.FINISHED.name().equals(f.getProfitSharing()))
                .filter(f -> {
                    LocalDate flowDate = f.getCreateTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
                    return flowDate.getYear() == currentDate.getYear() && flowDate.getMonth() == currentDate.getMonth();
                })
                .mapToDouble(flow -> StringUtils.isNotBlank(flow.getLowerCommissId()) && flow.getLowerCommissId().equals(UserContext.getCurrentId()) ? flow.getLowerCommiss() : flow.getLowerSubCommiss())
                .sum();
        result.setTotalMoney(BigDecimal.valueOf(finishedMoney).setScale(2, RoundingMode.DOWN));
        result.setWaitForSettlementMoney(BigDecimal.valueOf(waitCompleteMoney).setScale(2, RoundingMode.DOWN));
        result.setDateTotalMoney(BigDecimal.valueOf(currentMonthMoney).setScale(2, RoundingMode.DOWN));
        return result;
    }

    /**
     * 收益记录
     * @param incomeRecordReq 类型
     * @return 收益记录
     */
    @Override
    public ResultMessage<Object> incomeRecord(IncomeRecordReq incomeRecordReq) {
        Page<OrderFlow> flowPage = super.page(PageUtil.initPage(incomeRecordReq), this.createWrapper(incomeRecordReq));
        Page<IncomeRecordVO> resultPage = this.conversion(flowPage, null);
        if (CollectionUtil.isNotEmpty(resultPage.getRecords())) {
            for (IncomeRecordVO resultVO : resultPage.getRecords()) {
                if (resultVO.getDescription().contains(OrderConstant.LOWER_TYPE_01)) {
                    resultVO.setMoney(resultVO.getLowerCommiss());
                } else {
                    resultVO.setMoney(resultVO.getLowerSubCommiss());
                }
                resultVO.setDescription(resultVO.getDescription() + "支付￥" + resultVO.getFlowPrice());
                if (ProfitSharingStatusEnum.FINISHED.name().equals(resultVO.getProfitSharing())) {
                    resultVO.setStatusName("已结算");
                }
                if (ProfitSharingStatusEnum.WAIT_COMPLETE.name().equals(resultVO.getProfitSharing()) || ProfitSharingStatusEnum.PROCESSING.name().equals(resultVO.getProfitSharing())) {
                    resultVO.setStatusName("待结算");
                }
                if (ProfitSharingStatusEnum.ORDER_CANCEL.name().equals(resultVO.getProfitSharing()) || ProfitSharingStatusEnum.AFTER_SALE.name().equals(resultVO.getProfitSharing())) {
                    resultVO.setStatusName("用户退单");
                }
            }
        }
        return ResultUtil.data(resultPage);
    }

    /**
     * 数据转换
     * @param flowPage 源数据
     * @return 目标数据
     */
    private Page<IncomeRecordVO> conversion(Page<OrderFlow> flowPage, Integer isUnion) {
        if (CollectionUtil.isEmpty(flowPage.getRecords())) {
            return new Page<>();
        }
        Page<IncomeRecordVO> result = new Page<>();
        BeanUtil.copyProperties(flowPage, result);
        List<IncomeRecordVO> recordVOList = new ArrayList<>();

        List<String> orderSnList = flowPage.getRecords().stream().map(OrderFlow::getOrderSn).collect(Collectors.toList());
        List<String> userIdList = flowPage.getRecords().stream().map(OrderFlow::getMemberId).collect(Collectors.toList());
        List<User> userList = userClient.selectUserListByIds(userIdList);
        List<OrderItem> orderItemList = orderItemService.list(new LambdaQueryWrapper<OrderItem>().in(OrderItem::getOrderSn, orderSnList));
        Map<String, List<OrderItem>> orderItemMap = null;
        if (CollectionUtil.isNotEmpty(orderItemList)) {
            orderItemMap = orderItemList.stream().collect(Collectors.groupingBy(OrderItem::getOrderSn));
        }

        for (OrderFlow orderFlow : flowPage.getRecords()) {
            IncomeRecordVO vo = new IncomeRecordVO();
            vo.setTime(orderFlow.getCreateTime());
            vo.setProfitSharing(orderFlow.getProfitSharing());
            if (orderFlow.getFlowPrice() != null) {
                vo.setFlowPrice(BigDecimal.valueOf(orderFlow.getFlowPrice()));
            }
            if (orderFlow.getLowerSubCommiss() != null) {
                vo.setLowerSubCommiss(BigDecimal.valueOf(orderFlow.getLowerSubCommiss()));
            }
            if (orderFlow.getLowerCommiss() != null) {
                vo.setLowerCommiss(BigDecimal.valueOf(orderFlow.getLowerCommiss()));
            }
            if (orderFlow.getCastellanGreenScore() != null) {
                vo.setCastellanGreenScore(BigDecimal.valueOf(orderFlow.getCastellanGreenScore()));
            }
            if (orderFlow.getUnionGreenScore() != null && orderFlow.getUnionGreenScore() > 0) {
                vo.setUnionGreenScore(orderFlow.getUnionGreenScore());
            }
            StringBuilder str = new StringBuilder();
            if (null == isUnion) {
                if (orderFlow.getLowerCommissId() != null && orderFlow.getLowerCommissId().equals(UserContext.getCurrentId())) {
                    str = new StringBuilder(OrderConstant.LOWER_TYPE_01);
                } else {
                    str = new StringBuilder(OrderConstant.LOWER_TYPE_02);
                }
            }

            if (CollectionUtil.isNotEmpty(userList)) {
                for (User user : userList) {
                    if (user.getId().equals(orderFlow.getMemberId())) {
                        str.append(user.getNickName()).append(StringPool.COMMA);
                    }
                }
            }
            if (CollectionUtil.isNotEmpty(orderItemMap)) {
                for (Map.Entry<String, List<OrderItem>> itemEntry : orderItemMap.entrySet()) {
                    if (StringUtils.isNotBlank(itemEntry.getKey()) && itemEntry.getKey().equals(orderFlow.getOrderSn())) {
                        String goodsName = itemEntry.getValue().stream().map(OrderItem::getGoodsName).collect(Collectors.joining(","));
                        if (null != isUnion) {
                            str.append("店主直推成交：").append(goodsName).append(StringPool.COMMA);
                        }else {
                            str.append("下单：").append(goodsName).append(StringPool.COMMA);
                        }
                    }
                }
            }
//            if (orderFlow.getFlowPrice() != null && type == 1) {
//                str.append("支付￥").append(orderFlow.getFlowPrice());
//            }
            vo.setDescription(str.toString());
            recordVOList.add(vo);
        }
        result.setRecords(recordVOList);
        return result;
    }

    /**
     * 创建查询条件
     * @param incomeRecordReq 条件
     * @return 创建查询条件
     */
    private LambdaQueryWrapper<OrderFlow> createWrapper(IncomeRecordReq incomeRecordReq) {
        LambdaQueryWrapper<OrderFlow> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (incomeRecordReq.getType() != null) {
            //1已结算，2待结算，3结算取消
            if (OrderConstant.INCOME_RECORD_TYPE_1.equals(incomeRecordReq.getType())) {
                lambdaQueryWrapper.eq(OrderFlow::getProfitSharing, ProfitSharingStatusEnum.FINISHED.name());
            }
            if (OrderConstant.INCOME_RECORD_TYPE_2.equals(incomeRecordReq.getType())) {
                lambdaQueryWrapper.in(OrderFlow::getProfitSharing, ProfitSharingStatusEnum.WAIT_COMPLETE.name(), ProfitSharingStatusEnum.PROCESSING.name());
            }
            if (OrderConstant.INCOME_RECORD_TYPE_3.equals(incomeRecordReq.getType())) {
                lambdaQueryWrapper.in(OrderFlow::getProfitSharing, ProfitSharingStatusEnum.ORDER_CANCEL.name(), ProfitSharingStatusEnum.AFTER_SALE.name());
            }
        }
        //1今天，2昨天，3本月，4上月，5全部（不传默认）
        if (incomeRecordReq.getPayTimeType() != null) {
            switch (incomeRecordReq.getPayTimeType()) {
                case 1 -> { // 今天
                    LocalDate today = LocalDate.now();
                    lambdaQueryWrapper.between(OrderFlow::getCreateTime, today.atStartOfDay(), today.atTime(23, 59, 59));
                }
                case 2 -> { // 昨天
                    LocalDate yesterday = LocalDate.now().minusDays(1);
                    lambdaQueryWrapper.between(OrderFlow::getCreateTime, yesterday.atStartOfDay(), yesterday.atTime(23, 59, 59));
                }
                case 3 -> { // 本月
                    YearMonth currentMonth = YearMonth.now();
                    LocalDate firstDayOfMonth = currentMonth.atDay(1);
                    LocalDate lastDayOfMonth = currentMonth.atEndOfMonth();
                    lambdaQueryWrapper.between(OrderFlow::getCreateTime, firstDayOfMonth.atStartOfDay(), lastDayOfMonth.atTime(23, 59, 59));
                }
                case 4 -> { // 上月
                    YearMonth previousMonth = YearMonth.now().minusMonths(1);
                    LocalDate firstDayOfPreviousMonth = previousMonth.atDay(1);
                    LocalDate lastDayOfPreviousMonth = previousMonth.atEndOfMonth();
                    lambdaQueryWrapper.between(OrderFlow::getCreateTime, firstDayOfPreviousMonth.atStartOfDay(), lastDayOfPreviousMonth.atTime(23, 59, 59));
                }
                default -> {
                }
            }
        }
        //查询开始时间
        if (incomeRecordReq.getBeginDate() != null) {
            lambdaQueryWrapper.ge(OrderFlow::getCreateTime, incomeRecordReq.getBeginDate());
        }
        //查询结束时间
        if (incomeRecordReq.getEndDate() != null) {
            lambdaQueryWrapper.le(OrderFlow::getCreateTime, incomeRecordReq.getEndDate());
        }
        //获取下级id  +  下级的下级id
//        String uids = userClient.callGetSubordinatesAndSubSubordinates(UserContext.getCurrentId());
//        log.info("createWrapper  uidList === {} ", uids);
//        if (StringUtils.isEmpty(uids)) {
//            return lambdaQueryWrapper.eq(OrderFlow::getId, -1);
//        }
        lambdaQueryWrapper.and(q -> q.eq(OrderFlow::getLowerCommissId, UserContext.getCurrentId())
                .or().eq(OrderFlow::getLowerSubCommissId, UserContext.getCurrentId()));
//        lambdaQueryWrapper.in(OrderFlow::getMemberId, (Object[]) uids.split(","));
        lambdaQueryWrapper.and(q -> q.isNotNull(OrderFlow::getLowerCommissId).and(q2 -> q2.ne(OrderFlow::getLowerCommissId, "")));
        lambdaQueryWrapper.orderByDesc(OrderFlow::getCreateTime);
        lambdaQueryWrapper.gt(OrderFlow::getLowerCommiss, 0);
        return lambdaQueryWrapper;
    }

    @Override
    public List<OrderFlow> selectSubUserFlowPrice(SubUserFlowPriceVO subUserFlowPriceVO) {
        return baseMapper.selectSubUserFlowPrice(subUserFlowPriceVO);
    }

    /**
     * 直销业绩列表
     * @param dto
     * @return
     */
    @Override
    public OrderFlowVO getOrderFlowsByDisMemberId(OrderFlowQueryDTO dto) {
        this.processParams(dto);
        OrderFlowVO vo = new OrderFlowVO();
        //这里根据userIds查询订单信息
        Page<OrderItemViewVO> page = this.getOrderItemBydto(dto);
        if (null != page) {
            vo.setFlowVOPage(page);
            //查询已结算/未结算总业绩
            Double sum = baseMapper.sumOrderPriceByDto(dto);
            vo.setFinishedTotal(sum);
        }
        return vo;
    }

    /**
     * 根据userids查询订单列表
     * @param dto
     * @return
     */
    public Page<OrderItemViewVO> getOrderItemBydto(OrderFlowQueryDTO dto) {
        //直推订单列表/直推佣金
        Page<OrderItemViewVO> voPage = baseMapper.getOrderItemBydto(new Page(dto.getPageNumber(), dto.getPageSize()), dto);
        if (CollUtil.isNotEmpty(voPage.getRecords())) {
            this.processResultProfitSharing(voPage.getRecords());
        }
        return voPage;
    }

    /**
     * 处理返回结算状态
     * @param list
     */
    public void processResultProfitSharing(List<OrderItemViewVO> list) {
        list.stream().forEach(e -> {
            if (e.getProfitSharing().equals(ProfitSharingStatusEnum.PROCESSING.name()) || e.getProfitSharing().equals(ProfitSharingStatusEnum.WAIT_COMPLETE.name())) {
                e.setProfitSharing("待结算");
            } else if (e.getProfitSharing().equals(ProfitSharingStatusEnum.FINISHED.name())) {
                e.setProfitSharing("已结算");
            } else if (e.getProfitSharing().equals(ProfitSharingStatusEnum.ORDER_CANCEL.name()) || e.getProfitSharing().equals(ProfitSharingStatusEnum.AFTER_SALE.name())) {
                e.setProfitSharing("已退单");
            }
        });
    }

    /**
     * 查询佣金收益列表
     * @param dto
     * @return
     */
    @Override
    public OrderFlowVO getTotalCommissByDisMemberId(OrderFlowQueryDTO dto) {
        this.processParams(dto);
        OrderFlowVO vo = new OrderFlowVO();
        Page<OrderItemViewVO> page = baseMapper.getTotalCommissByDisMemberId(new Page(dto.getPageNumber(), dto.getPageSize()), dto);
        if (CollUtil.isNotEmpty(page.getRecords())) {
            this.processResultProfitSharing(page.getRecords());
            vo.setFlowVOPage(page);
            //查询已结算/未结算总佣金
            Double sum = baseMapper.sumOrderComisseByDto(dto);
            vo.setFinishedTotal(sum);
        }
        return vo;
    }

    /**
     * 参数整理
     */
    public void processParams(OrderFlowQueryDTO dto) {
        if (dto.getProfitSharingType() == null) {
            throw new ServiceException("结算状态不可为空");
        }
        //分账状态: 已结算,待结算,已退单
        if (dto.getProfitSharingType() != null && dto.getProfitSharingType() == 1) {
            dto.setProfitSharing("'" + ProfitSharingStatusEnum.PROCESSING.name() + "','" + ProfitSharingStatusEnum.WAIT_COMPLETE.name() + "'");
        } else if (dto.getProfitSharingType() != null && dto.getProfitSharingType() == 2) {
            dto.setProfitSharing(ProfitSharingStatusEnum.FINISHED.name());
        } else if (dto.getProfitSharingType() != null && dto.getProfitSharingType() == 3) {
            dto.setProfitSharing("'" + ProfitSharingStatusEnum.ORDER_CANCEL.name() + "','" + ProfitSharingStatusEnum.AFTER_SALE.name() + "'");
        }
    }


    /**
     * 根据userIds查询订单数
     *
     * @return
     */
    public Map<String, Integer> selectCountOrderByUserIds(List<String> userids, String parentId) {
        List<DisOrderFlowVO> list = baseMapper.selectCountOrderByUserIds(userids, parentId);
        if (CollUtil.isNotEmpty(list)) {
            //转成map
            return list.stream().collect(Collectors.toMap(DisOrderFlowVO::getMemberId, v -> v.getOrderCount()));
        }
        return null;
    }

    /**
     * 本月消费数
     * @param userIdList
     * @return
     */
    @Override
    public Map<String, Double> selectCurrentConsumptionByUserIds(List<String> userIdList, String parentId) {
        List<DisOrderFlowVO> list = baseMapper.selectCurrentConsumptionByUserIds(userIdList, parentId);
        if (CollUtil.isNotEmpty(list)) {
            //转成map
            return list.stream().collect(Collectors.toMap(DisOrderFlowVO::getMemberId, v -> v.getNum()));
        }
        return null;
    }

    /**
     * 累计消费数
     * @param userIdList
     * @return
     */
    @Override
    public Map<String, Double> selectCumulativeConsumptionByUserIds(List<String> userIdList, String parentId) {
        List<DisOrderFlowVO> list = baseMapper.selectCumulativeConsumptionByUserIds(userIdList, parentId);
        if (CollUtil.isNotEmpty(list)) {
            //转成map
            return list.stream().collect(Collectors.toMap(DisOrderFlowVO::getMemberId, v -> v.getNum()));
        }
        return null;
    }

    @Override
    public Page<IncomeRecordVO> directPushOrderList(DirectPushOrderParams pushOrderParams) {
        Page<OrderFlow> orderPage = super.page(PageUtil.initPage(pushOrderParams), this.createWrapperDirectPushOrderList(pushOrderParams));
        Page<IncomeRecordVO> resultPage = this.conversion(orderPage, null);
        if (CollectionUtil.isNotEmpty(resultPage.getRecords())) {
            for (IncomeRecordVO resultVO : resultPage.getRecords()) {
                resultVO.setMoney(resultVO.getFlowPrice());
                if (ProfitSharingStatusEnum.FINISHED.name().equals(resultVO.getProfitSharing())) {
                    resultVO.setStatusName("已结算");
                }
//                if (ProfitSharingStatusEnum.WAIT_COMPLETE.name().equals(resultVO.getProfitSharing())) {
//                    resultVO.setStatusName("待订单完成");
//                }
                if (ProfitSharingStatusEnum.PROCESSING.name().equals(resultVO.getProfitSharing()) || ProfitSharingStatusEnum.WAIT_COMPLETE.name().equals(resultVO.getProfitSharing())) {
                    resultVO.setStatusName("待结算");
                }
                if (ProfitSharingStatusEnum.ORDER_CANCEL.name().equals(resultVO.getProfitSharing()) || ProfitSharingStatusEnum.AFTER_SALE.name().equals(resultVO.getProfitSharing())) {
                    resultVO.setStatusName("用户退单");
                }
            }
        }
        return resultPage;
    }

    /**
     * 构建直推订单的查询条件
     * @param pushOrderParams 参数
     * @return 条件
     */
    private LambdaQueryWrapper<OrderFlow> createWrapperDirectPushOrderList(DirectPushOrderParams pushOrderParams) {
        LambdaQueryWrapper<OrderFlow> queryWrapper = new LambdaQueryWrapper<>();
        //直推用户
//        List<String> buyerIdList = null;
//        Map<String, List<String>> listMap = userClient.selectChildUserIdsByMemberIds(Collections.singletonList(UserContext.getCurrentId()));
//        if (CollectionUtil.isNotEmpty(listMap)) {
//            buyerIdList = listMap.get(UserContext.getCurrentId());
//        }
//        if (CollectionUtil.isEmpty(buyerIdList)) {
//            return queryWrapper.eq(OrderFlow::getId, -1);
//        }
        queryWrapper.in(OrderFlow::getLowerCommissId, UserContext.getCurrentId());
        //本月
        YearMonth currentMonth = YearMonth.now();
        LocalDate firstDayOfMonth = currentMonth.atDay(1);
        LocalDate lastDayOfMonth = currentMonth.atEndOfMonth();
        queryWrapper.between(OrderFlow::getCreateTime, firstDayOfMonth.atStartOfDay(), lastDayOfMonth.atTime(23, 59, 59));

        if (pushOrderParams.getType() != null) {
            //    vo.setStatusName("已结算");
            //    vo.setStatusName("待订单完成");
            //    vo.setStatusName("待结算");
            //    vo.setStatusName("用户退单");
            if (OrderConstant.DIRECT_PUSH_ORDER_TYPE_1.equals(pushOrderParams.getType())) {
                queryWrapper.eq(OrderFlow::getProfitSharing, ProfitSharingStatusEnum.FINISHED.name());
            }
            if (OrderConstant.DIRECT_PUSH_ORDER_TYPE_2.equals(pushOrderParams.getType())) {
                queryWrapper.in(OrderFlow::getProfitSharing, ProfitSharingStatusEnum.WAIT_COMPLETE.name(), ProfitSharingStatusEnum.PROCESSING.name());
            }
            if (OrderConstant.DIRECT_PUSH_ORDER_TYPE_3.equals(pushOrderParams.getType())) {
                queryWrapper.in(OrderFlow::getProfitSharing, ProfitSharingStatusEnum.WAIT_COMPLETE.name(), ProfitSharingStatusEnum.PROCESSING.name());
            }
            if (OrderConstant.DIRECT_PUSH_ORDER_TYPE_4.equals(pushOrderParams.getType())) {
                queryWrapper.in(OrderFlow::getProfitSharing, ProfitSharingStatusEnum.ORDER_CANCEL.name(), ProfitSharingStatusEnum.AFTER_SALE.name());
            }
        }
        if (StringUtils.isNotEmpty(pushOrderParams.getRegionId())) {
            LambdaQueryWrapper<Order> wrapperDirectPushOrderList = orderService.createWrapperDirectPushOrderList(pushOrderParams);
            wrapperDirectPushOrderList.select(Order::getId, Order::getSn);
            List<Order> orderList = orderService.list(wrapperDirectPushOrderList);
            if (CollectionUtil.isEmpty(orderList)) {
               return queryWrapper.eq(OrderFlow::getId, -1);
            }
            queryWrapper.in(OrderFlow::getOrderSn, orderList.stream().map(Order::getSn).collect(Collectors.toList()));
        }
        queryWrapper.orderByDesc(OrderFlow::getCreateTime);
        return queryWrapper;
    }

    /**
     * 根据工会地区查询本月工会经费
     * @param areaId
     * @return
     */
    @Override
    public Double getMonthUnionGreenScoreByAreaId (String areaId) {
        return this.baseMapper.getMonthUnionGreenScoreByAreaId(areaId);
    }

    /**
     * 获取直推订单金额
     * @param pushOrderParams 区域等搜索
     * @return 城主直推金额，与当前用户直推金额
     */
    @Override
    public DirectPushOrderMoneyVO directPushOrderMoney(DirectPushOrderParams pushOrderParams) {
        DirectPushOrderMoneyVO directPushOrderMoneyVO = new DirectPushOrderMoneyVO();
        BigDecimal defaultValue = BigDecimal.valueOf(0);
        directPushOrderMoneyVO.setCurrentMoneyTotal(defaultValue);
        directPushOrderMoneyVO.setMoneyDifference(defaultValue);
        directPushOrderMoneyVO.setCastellanMoneyTotal(defaultValue);
        directPushOrderMoneyVO.setIsCastellan(false);
        //本月时间
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        YearMonth currentMonth = YearMonth.now();
        LocalDate firstDayOfMonth = currentMonth.atDay(1);
        LocalDate lastDayOfMonth = currentMonth.atEndOfMonth();
        UserMoneyDTO castellanUserMoney = this.baseMapper.getUserMoney(null, pushOrderParams.getRegionId(), formatter.format(firstDayOfMonth.atStartOfDay()), formatter.format(lastDayOfMonth.atTime(23, 59, 59)));
        UserMoneyDTO currentUserMoney = this.baseMapper.getUserMoney(UserContext.getCurrentId(), pushOrderParams.getRegionId(), formatter.format(firstDayOfMonth.atStartOfDay()), formatter.format(lastDayOfMonth.atTime(23, 59, 59)));
        //城主直推订单金额
        if (castellanUserMoney != null) {
            directPushOrderMoneyVO.setCastellanMoneyTotal(BigDecimal.valueOf(castellanUserMoney.getMoney()));
        }
        //当前用户直推订单金额
        if (currentUserMoney != null) {
            directPushOrderMoneyVO.setCurrentMoneyTotal(BigDecimal.valueOf(currentUserMoney.getMoney()));
        }
        //当前用户就是预备城主
        if (castellanUserMoney != null && currentUserMoney != null && StringUtils.isNotBlank(castellanUserMoney.getId()) && castellanUserMoney.getId().equals(currentUserMoney.getId())) {
            directPushOrderMoneyVO.setIsCastellan(true);
        }
        //当前用户与城主，相差多少金额
        directPushOrderMoneyVO.setMoneyDifference(directPushOrderMoneyVO.getCastellanMoneyTotal().subtract(directPushOrderMoneyVO.getCurrentMoneyTotal()));
        return directPushOrderMoneyVO;
    }

    /**
     * 预备城主 + 当前区域城主
     * @param regionId 区域ID
     * @return
     */
    @Override
    public PremasterVO premaster(String regionId) {
        //当前区域城主
        PremasterVO result = new PremasterVO();
        CityDistribution castellan = userClient.getCastellan(regionId);
        log.info("castellan == {}", JSONObject.toJSONString(castellan));
        result.setCastellan(new PremasterDTO());
        if (castellan != null && StringUtils.isNotBlank(castellan.getId()) && StringUtils.isNotBlank(castellan.getMemberId())) {
            PremasterDTO premasterDTO = new PremasterDTO();
            User user = userClient.getById(castellan.getMemberId());
            premasterDTO.setId(castellan.getMemberId());
            premasterDTO.setName(user.getNickName());
            premasterDTO.setImage(user.getFace());
            result.setCastellan(premasterDTO);
        }
        //预备城主
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        YearMonth currentMonth = YearMonth.now();
        LocalDate firstDayOfMonth = currentMonth.atDay(1);
        LocalDate lastDayOfMonth = currentMonth.atEndOfMonth();
        List<UserMoneyDTO> premasterUserMoneyList = this.baseMapper.getUserMoneyList(null, regionId, formatter.format(firstDayOfMonth.atStartOfDay()), formatter.format(lastDayOfMonth.atTime(23, 59, 59)), 3);
        log.info("premasterUserMoneyList == {}", JSONObject.toJSONString(premasterUserMoneyList));
        result.setGetReadyCastellan(this.conversionPremaster(premasterUserMoneyList));

        //每月多少号更新
        Setting setting = settingClient.get(SettingEnum.DISTRIBUTION_SETTING.name());
        DistributionSetting distributionSetting = JSONUtil.toBean(setting.getSettingValue(), DistributionSetting.class);
        if (distributionSetting != null && StringUtils.isNotEmpty(distributionSetting.getMonthDay())) {
            result.setMonthDay(Integer.valueOf(distributionSetting.getMonthDay()));
        }
        String description = currentMonth.getMonthValue() + 1 + "月预备城主";
        result.setDescription(description);
        result.setPremasterMonth(result.getMonthDay() + "");
        return result;
    }

    private List<PremasterDTO> conversionPremaster(List<UserMoneyDTO> premasterUserMoneyList) {
        if (CollectionUtil.isEmpty(premasterUserMoneyList)) {
            return new ArrayList<>();
        }
        List<PremasterDTO> result = new ArrayList<>();
        for (UserMoneyDTO userMoneyDTO : premasterUserMoneyList) {
            if (StringUtils.isEmpty(userMoneyDTO.getMemberId()) || (userMoneyDTO.getMoney() == null || userMoneyDTO.getMoney() <= 0D)) {
                continue;
            }
            log.info("begin ========== ");
            User user = userClient.getById(userMoneyDTO.getMemberId());
            log.info("end =========== {}", JSONObject.toJSONString(user));
            PremasterDTO premasterDTO = new PremasterDTO();
            premasterDTO.setId(user.getId());
            premasterDTO.setPrice(BigDecimal.valueOf(userMoneyDTO.getMoney()));
            premasterDTO.setName(user.getNickName());
            premasterDTO.setImage(user.getFace());
            result.add(premasterDTO);
        }
        return result;
    }


    /**
     * 查询店主的直推业绩,佣金收益总数
     * @param memberIds
     * @return
     */
    @Override
    public List<OrderItemViewVO> getDistributionFlowPriceAndComissTotal(List<String> memberIds) {
        return baseMapper.getDistributionFlowPriceAndComissTotal(memberIds);
    }

    @Override
    public List<OrderItemViewVO> getDistributionFlowPriceAndComissTotalCurrentMonth(List<String> memberIds) {
        return baseMapper.getDistributionFlowPriceAndComissTotalCurrentMonth(memberIds);
    }

    @Override
    public List<OrderItemViewVO> getDistributionFlowPriceAndComissTotalLastMonth(List<String> memberIds) {
        return baseMapper.getDistributionFlowPriceAndComissTotalLastMonth(memberIds);
    }

    @Override
    public OrderItemViewVO getDistributionFlowPriceAndComissTotalByMonth(String memberId,String startTime,String endTime){
        return baseMapper.getDistributionFlowPriceAndComissTotalByMonth(memberId,startTime,endTime);
    }

    @Override
    public List<OrderItemViewVO> getDistributionFlowPriceAndComissTotalType(List<String> memberIds, Integer type) {
        return baseMapper.getDistributionFlowPriceAndComissTotalType(memberIds, type);
    }

    @Override
    public List<OrderItemViewVO> getDistributionFlowPriceAndComissTotalDistribution(List<String> memberIds) {
        return baseMapper.getDistributionFlowPriceAndComissTotalDistribution(memberIds);
    }

    /**
     * 查询当前区域下的订单流水统计
     *
     * @param regionId  区域ID
     * @param yearDate 年
     * @param monthDate 月
     */
    @Override
    public OrderFlowComputeVO orderFlowCompute(String regionId, Integer yearDate, Integer monthDate) {
        OrderFlowComputeVO result = new OrderFlowComputeVO();
        result.setReturnedOrder(0D);
        result.setCompleted(0D);
        result.setIncomeStatistics(BigDecimal.valueOf(0));
        result.setToBeCompleted(0D);

        OrderFlowQueryDTO queryDto = new OrderFlowQueryDTO();
        if (yearDate != null && monthDate != null) {
            YearMonth yearMonth = YearMonth.of(yearDate, monthDate);
            // 获取该月的开始时间和结束时间
            LocalDate startDate = yearMonth.atDay(1);
            LocalDateTime localDateTime = yearMonth.atEndOfMonth().atTime(23, 59, 59, 999);
            queryDto.setStartLocalDate(startDate);
            queryDto.setEndLocalDate(localDateTime.toLocalDate());
        } else {
            LocalDate localDate = LocalDate.now();
            queryDto.setStartLocalDate(LocalDate.of(localDate.getYear(), localDate.getMonth().getValue(), 1));
            queryDto.setEndLocalDate(queryDto.getStartLocalDate().plusMonths(1));
        }
        queryDto.setJoinAddressCode(regionId);
        queryDto.setMemberId(UserContext.getCurrentId());
        Map<String, BigDecimal> sumGreenScoreListMap = orderMapper.getCityDistributionSumGreenScore(queryDto);
        log.info("sumGreenScoreList == {}", JSONObject.toJSONString(sumGreenScoreListMap));
        if (CollectionUtil.isNotEmpty(sumGreenScoreListMap)) {
//            //已完成
//            BigDecimal bigDecimal = sumGreenScoreListMap.get(0);
            result.setCompleted(sumGreenScoreListMap.get("completed").doubleValue());
//            result.setCompleted();
//            //已退单
//            result.setReturnedOrder(sumGreenScoreListMap.get(2));
            result.setReturnedOrder(sumGreenScoreListMap.get("returnedOrder").doubleValue());
//            //待完成
//            result.setToBeCompleted(sumGreenScoreListMap.get(1));
            result.setToBeCompleted(sumGreenScoreListMap.get("toBeCompleted").doubleValue());
//            //收益统计
//            result.setIncomeStatistics(BigDecimal.valueOf(sumGreenScoreListMap.get(0)));
            result.setIncomeStatistics(sumGreenScoreListMap.get("completed"));
        }
        return result;
    }

    /**
     * 查询当前区域下的订单
     *
     * @param regionId 区域ID
     * @param type 查询类型
     */
    @Override
    public Page<IncomeRecordVO> orderFlowPage(String regionId, Integer isUnion, Integer type, PageVO pageVO) {
        LambdaQueryWrapper<Order> orderLambdaQueryWrapper = new LambdaQueryWrapper<>();
        orderLambdaQueryWrapper.like(Order::getConsigneeAddressIdPath, regionId);
        orderLambdaQueryWrapper.select(Order::getId, Order::getSn);
        List<Order> orderList = orderService.list(orderLambdaQueryWrapper);
        if (CollectionUtil.isEmpty(orderList)) {
            return new Page<>();
        }
        log.info("orderList == {}", JSONObject.toJSONString(orderList));
        LambdaQueryWrapper<OrderFlow> orderFlowLambdaQueryWrapper = new LambdaQueryWrapper<>();
        orderFlowLambdaQueryWrapper.in(OrderFlow::getOrderSn, orderList.stream().map(Order::getSn).collect(Collectors.toList()));
        if (type != null) {
            //1 已结算， 2 待完成  3 已退单
            if (type == 1) {
                orderFlowLambdaQueryWrapper.eq(OrderFlow::getProfitSharing, ProfitSharingStatusEnum.FINISHED.name());
            }
            if (type == 2) {
                orderFlowLambdaQueryWrapper.in(OrderFlow::getProfitSharing, ProfitSharingStatusEnum.PROCESSING.name(), ProfitSharingStatusEnum.WAIT_COMPLETE.name());
            }
            if (type == 3) {
                orderFlowLambdaQueryWrapper.in(OrderFlow::getProfitSharing, ProfitSharingStatusEnum.ORDER_CANCEL.name(), ProfitSharingStatusEnum.AFTER_SALE.name());
            }
        }
        if (null != isUnion) {
            orderFlowLambdaQueryWrapper.gt(OrderFlow::getUnionGreenScore, 0);
        }
//        else {
//            String currentId = UserContext.getCurrentId();
//            orderFlowLambdaQueryWrapper.eq(OrderFlow::getLowerCommissId, currentId);
//        }

        //本月
        YearMonth currentMonth = YearMonth.now();
        LocalDate firstDayOfMonth = currentMonth.atDay(1);
        LocalDate lastDayOfMonth = currentMonth.atEndOfMonth();
        orderFlowLambdaQueryWrapper.between(OrderFlow::getCreateTime, firstDayOfMonth.atStartOfDay(), lastDayOfMonth.atTime(23, 59, 59));
        orderFlowLambdaQueryWrapper.orderByDesc(OrderFlow::getCreateTime);

        Page<OrderFlow> orderFlowPage = super.page(PageUtil.initPage(pageVO) ,orderFlowLambdaQueryWrapper);
        log.info("orderFlowPage == {}", JSONObject.toJSONString(orderFlowPage));
        Page<IncomeRecordVO> resultPage = this.conversion(orderFlowPage, isUnion);
        log.info("resultPage == {}", JSONObject.toJSONString(resultPage));
        if (CollectionUtil.isNotEmpty(resultPage.getRecords())) {
            for (IncomeRecordVO resultVO : resultPage.getRecords()) {
                resultVO.setMoney(resultVO.getCastellanGreenScore());
                if (ProfitSharingStatusEnum.FINISHED.name().equals(resultVO.getProfitSharing())) {
                    resultVO.setStatusName("已结算");
                }
                if (ProfitSharingStatusEnum.WAIT_COMPLETE.name().equals(resultVO.getProfitSharing()) || ProfitSharingStatusEnum.PROCESSING.name().equals(resultVO.getProfitSharing())) {
                    resultVO.setStatusName("待完成");
                }
                if (ProfitSharingStatusEnum.ORDER_CANCEL.name().equals(resultVO.getProfitSharing()) || ProfitSharingStatusEnum.AFTER_SALE.name().equals(resultVO.getProfitSharing())) {
                    resultVO.setStatusName("已退单");
                }
            }
        }
        return resultPage;
    }

    /**
     * 获取工会成员本月业绩数据
     * @return
     */
    @Override
    public Page<OrderFlowDTO> getCurrentMonthByUnionMember (UnionOrderParams params) {
        QueryWrapper<OrderFlow> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotEmpty(params.getOrderSn()), "lof.order_sn", params.getOrderSn());
        if (StringUtils.isEmpty(params.getProfitSharing()) || "0".equals(params.getProfitSharing())) {
            queryWrapper.in("lof.profit_sharing", Arrays.asList(ProfitSharingStatusEnum.ORDER_CANCEL.name(),
                    ProfitSharingStatusEnum.WAIT_COMPLETE.name(), ProfitSharingStatusEnum.FINISHED.name(), ProfitSharingStatusEnum.AFTER_SALE.name()));
        }else {
            if (params.getProfitSharing().equals(ProfitSharingStatusEnum.ORDER_CANCEL.name())) {
                queryWrapper.in("lof.profit_sharing", Arrays.asList(ProfitSharingStatusEnum.ORDER_CANCEL.name(),
                        ProfitSharingStatusEnum.AFTER_SALE.name()));
            }else {
                queryWrapper.eq("lof.profit_sharing", params.getProfitSharing());
            }

        }
        queryWrapper.eq(StringUtils.isNotEmpty(params.getGoodsId()),"loi.goods_id", params.getGoodsId());
        queryWrapper.eq("lof.lower_commiss_id", params.getMemberId());
        queryWrapper.gt("lof.union_green_score", 0);
        return this.baseMapper.getCurrentMonthByMember(PageUtil.initPage(params), queryWrapper);
    }

    /**
     * 根据工会成员统计本月已结算金额、待结算金额、退单金额
     * @param lowerCommissId
     * @return
     */
    @Override
    public PerformanceDetailVO getCurrentMonthStatisticsByMember (UnionOrderParams params) {
        LambdaQueryWrapper<OrderFlow> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isEmpty(params.getProfitSharing()) || "0".equals(params.getProfitSharing())) {
            queryWrapper.in(OrderFlow::getProfitSharing, Arrays.asList(ProfitSharingStatusEnum.FINISHED.name(), ProfitSharingStatusEnum.WAIT_COMPLETE.name(), ProfitSharingStatusEnum.ORDER_CANCEL.name(), ProfitSharingStatusEnum.AFTER_SALE.name()));
        }else {
            if (params.getProfitSharing().equals(ProfitSharingStatusEnum.ORDER_CANCEL.name())) {
                queryWrapper.in(OrderFlow::getProfitSharing, Arrays.asList(ProfitSharingStatusEnum.ORDER_CANCEL.name(),
                        ProfitSharingStatusEnum.AFTER_SALE.name()));
            }else {
                queryWrapper.eq(OrderFlow::getProfitSharing, params.getProfitSharing());
            }
        }

        queryWrapper.eq(StringUtils.isNotEmpty(params.getOrderSn()), OrderFlow::getOrderSn, params.getOrderSn());
        queryWrapper.eq(OrderFlow::getIsPay, true);
        queryWrapper.gt(OrderFlow::getUnionGreenScore, 0);
        return this.baseMapper.getCurrentMonthStatisticsByMember(queryWrapper, params.getMemberId());
    }

    /**
     * 获取工会成员本月业绩数据
     * @return
     */
    @Override
    public Page<OrderFlowDTO> getLastMonthByUnionMember (UnionOrderParams params) {
        QueryWrapper<OrderFlow> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotEmpty(params.getOrderSn()), "lof.order_sn", params.getOrderSn());
        if (StringUtils.isEmpty(params.getProfitSharing()) || "0".equals(params.getProfitSharing())) {
            queryWrapper.in("lof.profit_sharing", Arrays.asList(ProfitSharingStatusEnum.ORDER_CANCEL.name(),
                    ProfitSharingStatusEnum.WAIT_COMPLETE.name(), ProfitSharingStatusEnum.FINISHED.name(), ProfitSharingStatusEnum.AFTER_SALE.name()));
        }else {
            if (params.getProfitSharing().equals(ProfitSharingStatusEnum.ORDER_CANCEL.name())) {
                queryWrapper.in("lof.profit_sharing", Arrays.asList(ProfitSharingStatusEnum.ORDER_CANCEL.name(),
                        ProfitSharingStatusEnum.AFTER_SALE.name()));
            }else {
                queryWrapper.eq("lof.profit_sharing", params.getProfitSharing());
            }

        }
        queryWrapper.eq(StringUtils.isNotEmpty(params.getGoodsId()),"loi.goods_id", params.getGoodsId());
        queryWrapper.eq("lof.lower_commiss_id", params.getMemberId());
        queryWrapper.gt("lof.union_green_score", 0);
        return this.baseMapper.getLastMonthByMember(PageUtil.initPage(params), queryWrapper);
    }

    /**
     * 根据工会成员统计上月已结算金额、待结算金额、退单金额
     * @param lowerCommissId
     * @return
     */
    @Override
    public PerformanceDetailVO getLastMonthStatisticsByMember (UnionOrderParams params) {
        LambdaQueryWrapper<OrderFlow> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isEmpty(params.getProfitSharing()) || "0".equals(params.getProfitSharing())) {
            queryWrapper.in(OrderFlow::getProfitSharing, Arrays.asList(ProfitSharingStatusEnum.FINISHED.name(), ProfitSharingStatusEnum.WAIT_COMPLETE.name(), ProfitSharingStatusEnum.ORDER_CANCEL.name(), ProfitSharingStatusEnum.AFTER_SALE.name()));
        }else {
            if (params.getProfitSharing().equals(ProfitSharingStatusEnum.ORDER_CANCEL.name())) {
                queryWrapper.in(OrderFlow::getProfitSharing, Arrays.asList(ProfitSharingStatusEnum.ORDER_CANCEL.name(),
                        ProfitSharingStatusEnum.AFTER_SALE.name()));
            }else {
                queryWrapper.eq(OrderFlow::getProfitSharing, params.getProfitSharing());
            }

        }
        queryWrapper.eq(StringUtils.isNotEmpty(params.getOrderSn()), OrderFlow::getOrderSn, params.getOrderSn());
        queryWrapper.eq(OrderFlow::getIsPay, true);
        return this.baseMapper.getLastMonthStatisticsByMember(queryWrapper, params.getMemberId());
    }

    /**
     * 获取工会业绩数据
     * @return
     */
    @Override
    public Page<OrderFlow> getUnionMoneyDetail (UnionOrderParams params) {
        QueryWrapper<OrderFlow> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotEmpty(params.getOrderSn()), "lof.order_sn", params.getOrderSn());
        if (StringUtils.isEmpty(params.getProfitSharing())) {
            queryWrapper.in("lof.profit_sharing", Arrays.asList(ProfitSharingStatusEnum.ORDER_CANCEL.name(),
                    ProfitSharingStatusEnum.WAIT_COMPLETE.name(), ProfitSharingStatusEnum.FINISHED.name(), ProfitSharingStatusEnum.AFTER_SALE.name()));
        }else {
            if (params.getProfitSharing().equals(ProfitSharingStatusEnum.ORDER_CANCEL.name())) {
                queryWrapper.in("lof.profit_sharing", Arrays.asList(ProfitSharingStatusEnum.ORDER_CANCEL.name(),
                        ProfitSharingStatusEnum.AFTER_SALE.name()));
            }else {
                queryWrapper.eq("lof.profit_sharing", params.getProfitSharing());
            }
        }
        queryWrapper.eq(StringUtils.isNotEmpty(params.getMemberId()), "lof.member_id", params.getMemberId());
        queryWrapper.gt("lof.union_green_score", 0);
        Page<OrderFlow> page = this.baseMapper.getUnionMoneyDetail(PageUtil.initPage(params),params.getMonth(),params.getRegionId(), queryWrapper);
        /*page.getRecords().forEach(orderFlow -> {
            if (null != orderFlow.getUnionCommissType() && orderFlow.getUnionCommissType() == 1) {
                OperationCenter operationCenter = operationCenterClient.getByAddressId(params.getProvinceId());
                GreenContributionInfo greenContributionInfo = new GreenContributionInfo();
                greenContributionInfo.setUserId(operationCenter.getUserId());
                greenContributionInfo.setOrderSn(orderFlow.getOrderSn());
                greenContributionInfo.setType(GreenAmountInfoTypeEnum.AUTO_DIVIDEND.name());
                greenContributionInfo.setStatus(GreenAmountInfoStatusEnum.INCOME.name());
                greenContributionInfo.setUserType(SceneEnums.OPERATION_CENTER.name());
                GreenContributionInfo gcb = greenClient.getGreenContributionInfo(greenContributionInfo);
                if (null != gcb) {
                    orderFlow.setUnionGreenScore(Double.valueOf(String.valueOf(gcb.getUmber())));
                }
            }
        });*/
        return page;
    }

    /**
     * 城主历史收益
     *
     * @return 城主历史收益
     */
    @Override
    public Page<HistoryEarningsVO> historyEarnings(PageVO pageVO) {
        Page<CityDistribution> cityDistributionPage = userClient.historyEarnings(pageVO.getPageNumber(), pageVO.getPageSize());
        Page<HistoryEarningsVO> resultPage = new Page<>();
        BeanUtil.copyProperties(cityDistributionPage, resultPage);

        List<HistoryEarningsVO> resultList = new ArrayList<>();
        for (CityDistribution cityDistribution : cityDistributionPage.getRecords()) {
            HistoryEarningsVO historyEarningsVO = new HistoryEarningsVO();
            historyEarningsVO.setList(new ArrayList<>());
            historyEarningsVO.setYearMonth(cityDistribution.getYearDate() + "/" + cityDistribution.getMonthDate());
            if (StringUtils.isEmpty(cityDistribution.getDistrictCodeGroup())) {
                continue;
            }
            List<OrderFlowComputeVO> computeVOList = new ArrayList<>();
            String[] districtCodeGroup = cityDistribution.getDistrictCodeGroup().split(",");
            String[] nameGroup = cityDistribution.getNameGroup().split("/");
            for (int index = 0; index < districtCodeGroup.length; index++) {
                OrderFlowComputeVO orderFlowComputeVO = this.orderFlowCompute(districtCodeGroup[index], cityDistribution.getYearDate(), cityDistribution.getMonthDate());
                //获取发放状态
                CityDistribution castellan = userClient.getCastellanByCodeYearMonth(districtCodeGroup[index], cityDistribution.getYearDate(), cityDistribution.getMonthDate());
                log.info("获取发放状态 castellan = {}", JSONObject.toJSONString(castellan));
                orderFlowComputeVO.setIssue(false);
                if (castellan != null && castellan.getComissStatus() != null && castellan.getComissStatus() == 2) {
                    orderFlowComputeVO.setIssue(true);
                }
                //发放类型 :
                orderFlowComputeVO.setIsGreen(castellan != null && castellan.getCommissType() != null ?  castellan.getCommissType(): 1);
                //获取贡献值
                orderFlowComputeVO.setContributionValue(BigDecimal.valueOf(0));
                if (castellan != null) {
                    BigDecimal contributionValue = this.computeContributionValue(castellan);
                    log.info("获取贡献值 castellan = {}", JSONObject.toJSONString(contributionValue));
                    if (contributionValue != null) {
                        orderFlowComputeVO.setContributionValue(contributionValue.setScale(2, RoundingMode.DOWN));
                    }
                }

                orderFlowComputeVO.setRegionName(nameGroup[index].replaceAll(",", ""));
                computeVOList.add(orderFlowComputeVO);
            }
            historyEarningsVO.setList(computeVOList);
            resultList.add(historyEarningsVO);
        }
        resultPage.setRecords(resultList);
        return resultPage;
    }

    /**
     * 获取贡献值
     * @param castellan 城主
     * @return 贡献值
     */
    private BigDecimal computeContributionValue(CityDistribution castellan) {
        //本月
        LocalDate begin = null;
        LocalDate end = null;
        if (castellan.getYearDate() != null && castellan.getMonthDate() != null) {
            YearMonth yearMonth = YearMonth.of(castellan.getYearDate(), castellan.getMonthDate());
            // 获取该月的开始时间和结束时间
            begin = LocalDate.of(yearMonth.getYear(), yearMonth.getMonth().getValue(), 1);
            end = begin.plusMonths(1);
        } else {
            LocalDate localDate = LocalDate.now();
            begin = LocalDate.of(localDate.getYear(), localDate.getMonth().getValue(), 1);
            end = begin.plusMonths(1);
        }
        log.info("begin == {}, end == {}", begin, end);
        return baseMapper.computeContributionValue(castellan.getMemberId(), castellan.getDistrictCode(), begin, end);
    }

    /**
     * 获取工会经费数据
     * @return
     */
    @Override
    public PerformanceDetailVO getUnionMoneyStatisticsDetail (UnionOrderParams params) {
        return this.baseMapper.getUnionMoneyStatisticsDetail(params.getMonth(),params.getRegionId());
    }

    /**
     * 获取工会本月分销订单数量、已完成订单数量、未完成订单数量、已退单数量
     * @return
     */
    @Override
    public PerformanceDetailVO getCurrentMonthUnionOrderCountByUnion (String areaId) {
        return this.baseMapper.getCurrentMonthUnionOrderCountByUnion(areaId);
    }

    /**
     * 获取工会上月分销订单数量、已完成订单数量、未完成订单数量、已退单数量
     * @return
     */
    @Override
    public PerformanceDetailVO getLastMonthUnionOrderByUnion (String areaId) {
        return this.baseMapper.getLastMonthUnionOrderByUnion(areaId);
    }

    /**
     * 根据id集合更新城主发放状态
     * @param ids
     * @return
     */
    @Override
    public int updateCommissStatusInIds(List<String> ids) {
        LambdaUpdateWrapper<OrderFlow> update = new LambdaUpdateWrapper<>();
        update.in(true, OrderFlow::getId, ids);
        update.set(true, OrderFlow::getCommissStatus, ComissStatusEnum.ALREADLY.type);
        update.set(true, OrderFlow::getCommissGiveTime, LocalDateTime.now());
        return super.update(update) ? 1 : 0;
    }


    /**
     * 查询工会成员本月业绩
     * @param memberId
     * @return
     */
    @Override
    public Double getCurrentMonthMoneyByMemberId (String memberId) {
        return baseMapper.getCurrentMonthMoneyByMemberId(memberId);
    }

    /**
     * 查询工会成员上月业绩
     * @param memberId
     * @return
     */
    @Override
    public Double getLastMonthMoneyByMemberId (String memberId) {
        return baseMapper.getLastMonthMoneyByMemberId(memberId);
    }

    /**
     * 根据id集合更新工会发放状态
     * @param ids
     * @return
     */
    @Override
    public int updateUnionCommissStatusInIds(List<String> ids, Integer unionCommissType) {
        LambdaUpdateWrapper<OrderFlow> update = new LambdaUpdateWrapper<>();
        update.in(true, OrderFlow::getId, ids);
        update.set(true, OrderFlow::getUnionCommissStatus, ComissStatusEnum.ALREADLY.type);
        update.set(true, OrderFlow::getUnionCommissGiveTime, LocalDateTime.now());
        update.set(OrderFlow::getUnionCommissType, unionCommissType);
        return super.update(update) ? 1 : 0;
    }

    /**
     * 工会经费发放记录
     * @param params
     * @return
     */
    @Override
    public Page<UnionMonthFundsVO> getUnionCommissByMonth (UnionOrderParams params) {
        // 先查询订单月份
        Page<UnionMonthFundsVO> monthList = orderService.getOrderMonth(params);
        if (!monthList.getRecords().isEmpty()) {
            monthList.getRecords().forEach(unionMonthFundsVO -> {
                List<String> orderSnList = orderService.getOrderSnByMonth(params.getRegionId(), unionMonthFundsVO.getYearMonth());
                PerformanceDetailVO performanceDetailVO = getUnionFundsByOrderSnMonth(orderSnList, unionMonthFundsVO.getYearMonth());
                if (performanceDetailVO != null) {
                    //unionMonthFundsVO.setSettlementPrice(performanceDetailVO.getSettlementMoney());
                    unionMonthFundsVO.setUnSettlementPrice(performanceDetailVO.getWaitSettlementMoney());
                    unionMonthFundsVO.setFunds(performanceDetailVO.getUnionFunds());
                    unionMonthFundsVO.setFundsType(performanceDetailVO.getCommissType());
                    if (StringUtils.isNotEmpty(performanceDetailVO.getStatus())) {
                        if ("2".equals(performanceDetailVO.getStatus())) {
                            unionMonthFundsVO.setStatus("已发放");
                        }else {
                            unionMonthFundsVO.setStatus("结算中");
                        }
                    }else {
                        unionMonthFundsVO.setStatus("结算中");
                    }

                    unionMonthFundsVO.setCreateTime(performanceDetailVO.getFundsTime());
                }
            });
        }
        return monthList;
    }

    public PerformanceDetailVO getUnionFundsByOrderSnMonth (List<String> orderSnList, String month) {
        LambdaQueryWrapper<OrderFlow> queryWrapper = new LambdaQueryWrapper<>();
        if (!orderSnList.isEmpty()) {
            queryWrapper.in(OrderFlow::getOrderSn, orderSnList);
            queryWrapper.eq(OrderFlow::getIsPay, true);
            queryWrapper.gt(OrderFlow::getUnionGreenScore, 0);
            return this.baseMapper.getUnionFundsByOrderSnMonth(queryWrapper, month);
        }
        return new PerformanceDetailVO();
    }

}